package com.topisv.tms.web.report;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springside.modules.web.Servlets;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.LogisticsCompanyService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.tools.DataTablesUtils;
import com.topisv.tms.tools.ExcelUtils;
import com.topisv.tms.utils.DateUtils;
import com.topisv.tms.utils.enums.StatusEnums;

import net.sf.json.JSONObject;

/**
 * 超区件—control
 * @author ch
 *
 */
@Controller
@RequestMapping(value = "/v2/firstPage")
public class FirstPageController{
	private static final Logger logger = LoggerFactory.getLogger(FirstPageController.class);
	@Autowired
	private CustomersService customersService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private EdiOrderItemService ediOrderItemService ; 
	@Autowired
	private LogisticsCompanyService logisticsCompanyService;

	/**
	 * 导向超区件管理页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toFirstPage")
	public String toFirstPage(Model model, ServletRequest request) {
		
		//查出当前用户关联的商家列表
		ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
		model.addAttribute("customerList",customerList);
		//by zhangweize 增加快递公司
		model.addAttribute("logisticsList", logisticsCompanyService.findAll());
		
		//如果是商家用户,初始化数据
		if(StatusEnums.user_type_customer.getStatus().equals(curUser.userType)){
			String customerCode=customerList.get(0).getCustomerCode();
			model.addAttribute("customerCode", customerCode);
			//初始化仓库数据
			List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
			model.addAttribute("warehouseList", warehouseList);
		}else if(StatusEnums.user_type_paiu.getStatus().equals(curUser.userType)){
			List<AreaGroup> warehouseList = areaGroupService.findByAreaGroups(curUser.areagroups);
			model.addAttribute("warehouseList", warehouseList);
		}
		return "report/firstPage";
	}
	
	
	 /**
	  * 数据源—待处理订单
	  * @param params
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	 @RequestMapping(value="/bindData_unhandle", method=RequestMethod.POST) 
     public void bindData_unhandle(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			//变量定义
			PrintWriter out=response.getWriter();
			JSONObject json=new JSONObject();
			Page<EdiOrder> page=null;
			
			//当前用户
			Map<String, Object> param=new HashMap<String, Object>();
            ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
            String customerCode = paramMap.get("customerCode");
            String warehouseCode = paramMap.get("warehouseCode");
            String dataRange = paramMap.get("dataRange");
            String orderno = paramMap.get("orderno");
            String cacode = paramMap.get("cacode");
			//封装查询参数
			if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
				String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			}else{
				param.put("customerCode", customerCode);
			}
			
			if(StringUtils.isEmpty(warehouseCode)){ //如果仓库编码为空，赋予默认权限值
				String areagroups=shiroUser.areagroups;
				param.put("areagroups", areagroups);
			}else{
				param.put("warehouseCode", warehouseCode);
			}
			
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             Date fromDate=dataMap.get("fromDate");
	             Date toDate=dataMap.get("toDate");
	             param.put("fromDate", fromDate);
	             param.put("toDate", toDate);
			}
          
			param.put("orderStatus", "ok");
			param.put("status", "pending");
			//未分配的也显示出来
			//EditBy yinglei_lian 2016.09.29 解决544
			//param.put("dispatchFlag", "1");
			param.put("orderno", orderno);
			
			//by zhangweize 增加快递公司查询条件
			param.put("companyCode", cacode);
			
			//查询
			int curPage=(start/length)+1;
			page = this.ediOrderService.loadPageOrder(param,curPage, length);
	        List<EdiOrder> eOrderList=page.getContent();
	        
	        //封装查询结果
	        json.put("aaData", eOrderList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
	        out.print(json);
        
		} catch (Exception e) {
			
		}
    } 
	 
	 /**
	  * 数据源—作业中订单
	  * @param params
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	 @RequestMapping(value="/bindData_working", method=RequestMethod.POST) 
     public void bindData_working(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			//变量定义
			PrintWriter out=response.getWriter();
			JSONObject json=new JSONObject();
			Page<WorkOrder> page=null;
			
			//当前用户
			Map<String, Object> param=new HashMap<String, Object>();
            ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);

			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
            String customerCode = paramMap.get("customerCode");
            String warehouseCode = paramMap.get("warehouseCode");
            String dataRange = paramMap.get("dataRange");
            String orderno = paramMap.get("orderno");
			String workStatus = paramMap.get("status");
			String cacode = paramMap.get("cacode");
			
			//封装查询参数
			if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
				String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			}else{
				param.put("customerCode", customerCode);
			}
			
			if(StringUtils.isEmpty(warehouseCode)){ //如果仓库编码为空，赋予默认权限值
				String areagroups=shiroUser.areagroups;
				param.put("areagroups", areagroups);
			}else{
				param.put("warehouseCode", warehouseCode);
			}
		
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             Date fromDate=dataMap.get("fromDate");
	             Date toDate=dataMap.get("toDate");
	             param.put("fromDate", fromDate);
	             param.put("toDate", toDate);
			}
            
			param.put("cancelStatus", "ok");
			param.put("status", "working");
			param.put("ordernoOrExpressno", orderno);
			param.put("workStatus", workStatus);
			param.put("companyCode", cacode);
			
			//查询
			int curPage=(start/length)+1;
			page = this.workOrderService.loadPageOrder(param,curPage, length);
	        List<WorkOrder> orderList=page.getContent();
	        
	        //封装查询结果
	        json.put("aaData", orderList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
	        out.print(json);
        
		} catch (Exception e) {
			
		}
    } 
	 
	 /**
	  * 数据源—已处理订单
	  * @param params
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	 @RequestMapping(value="/bindData_handled", method=RequestMethod.POST) 
     public void bindData_handled(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			//变量定义
			PrintWriter out=response.getWriter();
			JSONObject json=new JSONObject();
			Page<WorkOrder> page=null;
			
			//当前用户
			Map<String, Object> param=new HashMap<String, Object>();
            ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
            String customerCode = paramMap.get("customerCode");
            String warehouseCode = paramMap.get("warehouseCode");
            String dataRange = paramMap.get("dataRange");
            String orderno = paramMap.get("orderno");
            String cacode = paramMap.get("cacode");
			
			//封装查询参数
			if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
				String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			}else{
				param.put("customerCode", customerCode);
			}
			
			if(StringUtils.isEmpty(warehouseCode)){ //如果仓库编码为空，赋予默认权限值
				String areagroups=shiroUser.areagroups;
				param.put("areagroups", areagroups);
			}else{
				param.put("warehouseCode", warehouseCode);
			}
		
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             Date fromDate=dataMap.get("fromDate");
	             Date toDate=dataMap.get("toDate");
	             param.put("fromDate", fromDate);
	             param.put("toDate", toDate);
			}
            
			param.put("cancelStatus", "ok");
			param.put("status", "6");
			param.put("ordernoOrExpressno", orderno);
			param.put("companyCode", cacode);
			
			//查询
			int curPage=(start/length)+1;
			page = this.workOrderService.loadPageOrder(param,curPage, length);
	        List<WorkOrder> orderList=page.getContent();
	        
	        //封装查询结果
	        json.put("aaData", orderList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
	        out.print(json);
        
		} catch (Exception e) {
			
		}
    } 
	 
	 
	 /**
	  * 数据源—异常单
	  * @param params
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	 @RequestMapping(value="/bindData_exception", method=RequestMethod.POST) 
     public void bindData_exception(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			//变量定义
			PrintWriter out=response.getWriter();
			JSONObject json=new JSONObject();
			Page<WorkOrder> page=null;
			
			//当前用户
			Map<String, Object> param=new HashMap<String, Object>();
            ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
            String customerCode = paramMap.get("customerCode");
            String warehouseCode = paramMap.get("warehouseCode");
            String dataRange = paramMap.get("dataRange");
            String orderno = paramMap.get("orderno");
            String cacode = paramMap.get("cacode");
			
			//封装查询参数
			if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
				String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			}else{
				param.put("customerCode", customerCode);
			}
			
			if(StringUtils.isEmpty(warehouseCode)){ //如果仓库编码为空，赋予默认权限值
				String areagroups=shiroUser.areagroups;
				param.put("areagroups", areagroups);
			}else{
				param.put("warehouseCode", warehouseCode);
			}
		
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             Date fromDate=dataMap.get("fromDate");
	             Date toDate=dataMap.get("toDate");
	             param.put("fromDate", fromDate);
	             param.put("toDate", toDate);
			}
            
			param.put("cancelStatus", "exception");
			param.put("ordernoOrExpressno", orderno);
			param.put("companyCode", cacode);
			
			//查询
			int curPage=(start/length)+1;
			page = this.workOrderService.loadPageOrder(param,curPage, length);
	        List<WorkOrder> orderList=page.getContent();
	        
	        //封装查询结果
	        json.put("aaData", orderList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
	        out.print(json);
        
		} catch (Exception e) {
			
		}
    } 
	 /**
	  * 数据源—异常单
	  * @param params
	  * @param request
	  * @param response
	  * @throws Exception
	  */
	 @RequestMapping(value="bindData_sendOutFail", method=RequestMethod.POST) 
     public void bindData_sendOutFail(@RequestBody JSONParam[] paramJson,HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			//变量定义
			PrintWriter out=response.getWriter();
			JSONObject json=new JSONObject();
			Page<WorkOrder> page=null;
			
			//当前用户
			Map<String, Object> param=new HashMap<String, Object>();
            ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//客户端参数
			Map<String, String> paramMap = DataTablesUtils.convertToMap(paramJson);
			String sEcho = paramMap.get("sEcho");  
			int start = Integer.parseInt(paramMap.get("iDisplayStart"));
			int length = Integer.parseInt(paramMap.get("iDisplayLength")); 
            String customerCode = paramMap.get("customerCode");
            String warehouseCode = paramMap.get("warehouseCode");
            String dataRange = paramMap.get("dataRange");
            String orderno = paramMap.get("orderno");
            String cacode = paramMap.get("cacode");
			
			//封装查询参数
			if(StringUtils.isEmpty(customerCode)){ //如果商家编码为空，赋予默认权限值
				String customerCodes=this.customersService.loadCustomerByAuthority(shiroUser.jobuuid);
				param.put("customerCodes", customerCodes);
			}else{
				param.put("customerCode", customerCode);
			}
			
			if(StringUtils.isEmpty(warehouseCode)){ //如果仓库编码为空，赋予默认权限值
				String areagroups=shiroUser.areagroups;
				param.put("areagroups", areagroups);
			}else{
				param.put("warehouseCode", warehouseCode);
			}
		
			if(StringUtils.isNotEmpty(dataRange)){
				 Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	             Date fromDate=dataMap.get("fromDate");
	             Date toDate=dataMap.get("toDate");
	             param.put("fromDate", fromDate);
	             param.put("toDate", toDate);
			}
            
			param.put("sendOutStatus", "fail");
			param.put("cancelStatus", "ok");
			param.put("ordernoOrExpressno", orderno);
			param.put("companyCode", cacode);
			
			//查询
			int curPage=(start/length)+1;
			page = this.workOrderService.loadPageOrder(param,curPage, length);
	        List<WorkOrder> orderList=page.getContent();
	        
	        //封装查询结果
	        json.put("aaData", orderList);
	        json.put("sEcho", sEcho);
	        json.put("iTotalRecords", page.getTotalElements());
	        json.put("iTotalDisplayRecords", page.getTotalElements());
	        
	        out.print(json);
        
		} catch (Exception e) {
			
		}
    } 
	 
	 	/**
		 * 导出未处理订单
		 */
		@RequestMapping(value = "exportExcel")
		public String exportExcel_multi(Model model, ServletRequest request,ServletResponse response){
			FileInputStream f=null;
			OutputStream output=null;
			try {
				Date now=new Date();
				DateFormat df=new SimpleDateFormat("yyyyMMddhhmmss");
				
				// 查询商品
				Map<String, Object> param = Servlets.getParametersStartingWith(request, "_");
				String customerCode = (String) param.get("customerCode") ; 
				String warehouseCode = (String)param.get("warehouseCode") ;
				Customers customers = customersService.findByCustomerCode(customerCode) ;
				String dataRange = (String) param.get("dataRange") ; 
				Map<String, Date> dataMap=DateUtils.getDateRange(dataRange);
	            Date fromDate=dataMap.get("fromDate");
	            Date toDate=dataMap.get("toDate");
				List<EdiOrder> orderList = ediOrderService.findByCustomerCodeAndWarehouseCode(customerCode,warehouseCode, fromDate, toDate);
				//** 定义导出数据集合 *//
				List<Object[]> list = new ArrayList<Object[]>();
				SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				for (int i = 0; i < orderList.size(); i++) {
					try {
						EdiOrder orders=orderList.get(i);
						List<EdiOrderItem> ediOrderItems = ediOrderItemService.findByOrdeno(orders.getOrdeno()) ;
						for(EdiOrderItem ediOrderItem : ediOrderItems){
							Object[] obj = {
									orders.getCustomerOrdeno(),
									orders.getFromno(),
									orders.getCacode(),
									formatter.format(orders.getCrtime()),
									formatter.format(orders.getPlaceOrderTime()),
									orders.getRecena(),
									orders.getProvna(),
									orders.getCityna(),
									orders.getDistna(),
									orders.getAddres(),
									orders.getPostco(),
									orders.getMobile(),
									ediOrderItem.getSku(),
									ediOrderItem.getNam(),
									ediOrderItem.getPri(),
									ediOrderItem.getQty(),
									orders.getSpec(),
									//this.goodsJoin(orders.getOrdeno()),
									//formatter.format(orders.getAdtime()),
								    null
							};
							list.add(obj);
						}
					} catch (Exception e) {
						
						logger.error("error",e);
					}
				}
				
				//** 导出数据 *//
				String[] title = {"淘宝订单号", "ERP订单号", "快递方式","审单时间","支付时间","收货人姓名","省份","市","区","详细地址","邮编","手机号","SKU","商品名称","商品价格","商品数量","商品规格属性"};
				String filepath = customerCode+"_"+warehouseCode+"_ErrorOrder.xls";
				//String title_page=customers.getCustomerName()+"缺货订单表";
				ExcelUtils.writeExcel(title, filepath, df.format(now) , list); // 生成excel
				//** 把生成的excel文件读出字节返回给客户端 *//
				((HttpServletResponse)response).setHeader("Content-disposition", "attachment; filename="+ new String(filepath.getBytes("gb2312"),"utf-8"));
				f = new FileInputStream(ExcelUtils.TEMPPATH+filepath);
				byte[] fb = new byte[f.available()];
				f.read(fb);
				ByteArrayInputStream bais = new ByteArrayInputStream(fb);
				output =((HttpServletResponse)response).getOutputStream();
				int by = 0;
				while ((by = bais.read()) != -1) {
					output.write(by);
				}
				output.flush();
				
			} catch (Exception e) {
				return "error";
			}finally{
				if (output!=null) {
					try { output.close(); } catch (IOException e) {logger.error("error",e);}
				}
				if (f!=null) {
					try { f.close(); } catch (IOException e)  {logger.error("error",e);}
				}
			}
			return null;
		}
		/**
		 * 获取未处理订单对应商品拼接
		 */
		public String goodsJoin(String ordeno){
			List<EdiOrderItem> itemList = ediOrderItemService.findByOrdeno(ordeno) ;
			StringBuffer sb = new StringBuffer("") ;
			for(int i = 0;i<itemList.size();i++){
				EdiOrderItem orderItems= itemList.get(i) ;
				if(StringUtils.isNotBlank(orderItems.getNam())){
					sb.append(orderItems.getNam()).append("[").append(orderItems.getSku()).append("](").append(orderItems.getQty()).append(")_") ;
				}else{
					sb.append("[").append(orderItems.getSku()).append("](").append(orderItems.getQty()).append(")_") ;
				}
			}
			String sbToString ="";
			if(sb.length()>0){
				sbToString = sb.toString() ;
				sbToString = sbToString.substring(0,sbToString.length()-1) ;
			}
			return sbToString;
		}
	
		/**
		 * 添加京东快递单号
		 *
		 * @param 
		 * @return 
		 * @throws 
		 * @author Songlinhai
		 * @version 1.0.0
		 */
		@RequestMapping(value = "addExpressNo", method=RequestMethod.POST)
        public void addExpressNo(ServletRequest request, ServletResponse response){
            PrintWriter out = null;
            JSONObject json = null;
            String msg = null;
            String[] list = null;
            
            
		    try{
		       out = response.getWriter();
	           json = new JSONObject();
	           list = request.getParameterValues("expressNo[]");
           }catch(Exception e){
               logger.error("添加京东快递单号失败",e);
               json.put("content", "添加京东单号失败");
           }
		    
		    msg = ediOrderService.addExpressNo(list);
            
            if(msg == ""){
                json.put("content", "成功");
            }else{
                json.put("content", msg);
            }
            
            out.print(json.toString());
            
            
        }
}
